package com.wswy.wzcx.ui.module.oilprice

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.format.DateFormat
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.ui.loading.ILoadingView
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.R
import com.wswy.wzcx.model.ICity
import com.wswy.wzcx.model.WZCity
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.model.resp.OilPriceResp
import com.wswy.wzcx.module.LocManager
import com.wswy.wzcx.module.base.CBaseLoadingFragment
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.car.choose.ChooseCityActivity
import com.wswy.wzcx.utils.LunarCalender
import com.wswy.wzcx.utils.ResUtils
import kotlinx.android.synthetic.main.f_oil_price_fragment.*
import java.util.*

class TodayOilPriceFragment : CBaseLoadingFragment() {

    private companion object {
        const val REQ_CHOOSE_CITY = 201
    }

    override fun getConfigure(): ILoadingView.LoadingConfigure? {
        return null
    }

    override fun getLoadingFrameId(): Int {
        return R.id.root_content
    }

    private lateinit var oilPriceViewModel: OilViewModel

    private var titleAddressView:TextView?=null

    private lateinit var cloudAnimHelper: CloudAnimHelper

    override fun getContentLayoutId(): Int {
        return R.layout.f_oil_price_fragment
    }

    override fun getTitleRightView(context: Context): View? {

        return  TextView(context).apply {

            val dp16 = SizeUtils.dp2px(16f)

            textSize = 14f
            setTextColor(ContextCompat.getColor(context,R.color.textColorSecondary))
            setPadding(dp16,0,dp16,0)
            setCompoundDrawables(ContextCompat.getDrawable(context,R.drawable.ic_pin)?.apply {
                setBounds(0,0,dp16,dp16)
            },null,null,null)
            text = LocManager.getInstance().displayCityName
            gravity = Gravity.CENTER
            includeFontPadding = false

            setBackgroundResource(ResUtils.getSelectableItemBackground(context))
            isClickable = true

            setOnClickListener(clickChooseCity)
            layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.MATCH_PARENT)
        }.also {
            titleAddressView = it
        }
    }


    private val clickChooseCity = View.OnClickListener {

        startActivityForResult(ChooseCityActivity.startCityWZ(it.context), REQ_CHOOSE_CITY)

    }


    override fun getFragmentTitle(): String {
        return "今日油价"
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        oilPriceViewModel=provideViewModel(OilViewModel::class.java)
        oilPriceViewModel.onCreate()

        cloudAnimHelper = CloudAnimHelper(img_top_cloud1)

        showLoading(true)
        oilPriceViewModel.getOilPriceLiveData().observe(this, Observer {

            it?.run {


                if(inLoading()){
                    showLoading(true)
                }else if (isOk()){
                    showData()
                    it.data?.let {
                        showData(it)
                    }


                }else{

                }

            }

        })


        oilPriceViewModel.load()
        initViews()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == REQ_CHOOSE_CITY){

            val city = data?.getParcelableExtra<ICity>(Constants.EXTRA_DATA_CHOOSE_CITY)


            if (city is WZCity && !TextUtils.equals(city.cityName, titleAddressView?.getText())) {
                oilPriceViewModel.onChangeCity(city)
                oilPriceViewModel.load()
                titleAddressView?.text = city.cityName
            }

        }

    }


    private fun initViews(){
        //附近加油站
        tv_nearby_gas.setOnClickListener {
            RouterUtils.start(it.context,RPaths.LBS_GAS_STATION)
        }

        //调价趋势
        tv_see_trend.setOnClickListener {

            val map = oilPriceViewModel.getPriceVos()?:return@setOnClickListener

            if (map.isNotEmpty()){
                startActivity(RouterUtils.getIntent(it.context,0,RPaths.OIL_TREND).apply {
                    putExtra(Constants.EXTRA_DATA,Bundle().apply {
                        putParcelableArrayList("92#", map.get("92#"))
                        putParcelableArrayList("95#", map.get("95#"))
                        putParcelableArrayList("d0#", map.get("d0#"))
                    })
                })
            }


        }

        oilPriceViewModel.localCity?.let {
            titleAddressView?.text = it.cityName
        }


        val lc =LunarCalender()

        tv_today_date.text = "${DateFormat.format("yyyy-MM-dd", Date())} ${lc.week}"

        tv_g92_hint.text = SpannableStringBuilder().apply {
            append("92#").append(SpannableString(" 汽油").apply {
                setSpan(RelativeSizeSpan(0.5833f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }
        tv_g95_hint.text = SpannableStringBuilder().apply {
            append("95#").append(SpannableString(" 汽油").apply {
                setSpan(RelativeSizeSpan(0.5833f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }
        tv_d0_hint.text = SpannableStringBuilder().apply {
            append("0#").append(SpannableString(" 柴油").apply {
                setSpan(RelativeSizeSpan(0.5833f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }

    }

    private fun showData(oilPriceResp: OilPriceResp){

        cloudAnimHelper.start()

        tv_next_adjust_date.text = getString(R.string.oil_next_adjust_date,oilPriceResp.nextChangeTime)

        oilPriceResp.list?.sortedBy { it.createdDate }?.firstOrNull()?.run {


            tv_g92_value.text = SpannableStringBuilder().apply {
                append(g92?.toString()).append(SpannableString(" 元/升").apply {
                    setSpan(RelativeSizeSpan(0.5833f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    setSpan(ForegroundColorSpan(ContextCompat.getColor(AppContext.getContext(),R.color.textColorTertiary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                })
            }

            addUpOrDown(tv_g92_value,g92UpDown?:0)

            tv_g95_value.text = SpannableStringBuilder().apply {
                append(g95?.toString()).append(SpannableString(" 元/升").apply {
                    setSpan(RelativeSizeSpan(0.5833f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    setSpan(ForegroundColorSpan(ContextCompat.getColor(AppContext.getContext(),R.color.textColorTertiary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                })
            }

            addUpOrDown(tv_g95_value,g95UpDown?:0)

            if (d0?:0f == 0f){
                tv_g0_value.text = "--"
            }else{
                tv_g0_value.text = SpannableStringBuilder().apply {
                    append(d0?.toString()).append(SpannableString(" 元/升").apply {
                        setSpan(RelativeSizeSpan(0.5833f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                        setSpan(ForegroundColorSpan(ContextCompat.getColor(AppContext.getContext(),R.color.textColorTertiary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                }
            }



            addUpOrDown(tv_g0_value,d0UpDown?:0)
        }

    }

    private fun addUpOrDown(textView: TextView,upOrDown:Int){
        when(upOrDown){
            1 -> {
                textView.setCompoundDrawables(ContextCompat.getDrawable(AppContext.getContext(),R.drawable.f_oil_up)?.apply {
                    setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                },null,null,null)
            }
            -1 -> {
                textView.setCompoundDrawables(ContextCompat.getDrawable(AppContext.getContext(),R.drawable.f_oil_down)?.apply {
                    setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                },null,null,null)
            }
            else -> {
                textView.setCompoundDrawables(null,null,null,null)
            }
        }
    }

    override fun onDetach() {
        super.onDetach()


        if (this::cloudAnimHelper.isInitialized){
            cloudAnimHelper.stop()
        }
    }

}